﻿using Huirui.Cavan.Domain.MainBoundedContext.SalesModule;
using Huirui.Cavan.Domain.MainBoundedContext.SearchModule;
using System;
using System.Collections;
using Huirui.Cavan.Domain.Seedwork;
using System.Collections.Generic;
using Huirui.Cavan.Domain.MainBoundedContext.SystemModule;
using Huirui.Cavan.Application.MainBoundedContext.StockModule;
using System.Linq;
using Huirui.Cavan.Application.MainBoundedContext.SystemModule;
using Huirui.Cavan.Domain.MainBoundedContext.StockModule;
using System.Linq;
using Huirui.Cavan.Core.Extension;

namespace Huirui.Cavan.Application.MainBoundedContext.SalesModule
{
	#region SalesReturn

    public class SalesReturnAppService : BaseAppService<SalesReturn, string, SalesReturnSearch, ISalesReturnRepository>, ISalesReturnAppService
	{
        private ISalesAppService SalesAppService { get; set; }
        private IStockAppService StockAppService { get; set; }
        private IStockInOutTypeAppService StockInOutTypeAppService { get; set; }
        private Employee _employee;
        private Seller _seller;

        public BoolGenericResult<SalesReturn> AddReturnBySales(string salesCode, SalesReturn entity)
        {
            Init();
            BoolGenericResult<SalesReturn> result = new BoolGenericResult<SalesReturn>();
            this.SalesAppService = this.SpringContext.GetObject(SalesModuleConst.SALESAPPSERVICE) as ISalesAppService;
            Sale sale = this.SalesAppService.GetById(salesCode);
            IList<SalesReturn> oldSalesReturns = this.GetBySearch(SearchFactory.CreateSalesReturnSearch(salesCode)).ToList();

            _employee = this.EmployeeAppService.GetSingleBySearch(SearchFactory.CreateEmployeeSearch(entity.SaleEmployee.Id, SearchIdentifier.Code.EmployeeCode));
            _seller = new Seller(_employee);

            StockInOutType stockInOutType = this.StockInOutTypeAppService.GetById(4);

            result = _seller.ReturnProductFromCustomer(string.Empty, entity.ReturnDate, entity.Currency, entity.CurrencyRate, entity.TaxRate, entity.Remark, entity.DeliveryAddress, entity.CheckCode,
                entity.SaleEmployee, entity.Project, null, entity.Customer, entity.WareHouse, entity.Contact, entity.ContactTelephone, entity.StockInOut, sale, stockInOutType);

            if (result.IsSuccess)
            {
                IIDGenerateAppService idGenerateAppService = this.SpringContext.GetObject(SystemModuleConst.IDGENERATEAPPSERVICE, new object[] { _employee.Corporation }) as IIDGenerateAppService;
                result.Object.Id = idGenerateAppService.GenerateID(SystemIdentifier.ReceiptCodeRuleType.SalesReturn);
                result = base.Add(result.Object);
                foreach (StockInOutDetail siod in entity.StockInOut.StockInOutDetails)
                {
                    this.StockAppService.Update(siod.Stock);
                }
            }

            return result;
        }
	}
	#endregion
}